// H5端用户数据模型（普通用户）
import { Collection, ObjectId } from 'mongodb'
import { getDB } from '../config/database.js'

// H5用户接口定义
export interface H5User {
  _id?: ObjectId
  username: string
  email?: string
  password: string // 加密后的密码
  phone?: string
  avatar?: string
  createdAt?: Date
  updatedAt?: Date
}

/**
 * 获取H5用户集合
 */
export function getH5UsersCollection(): Collection<H5User> {
  const db = getDB()
  return db.collection<H5User>('h5users')
}

/**
 * 创建新的H5用户
 */
export async function createH5User(
  userData: Omit<H5User, '_id' | 'createdAt' | 'updatedAt'>
): Promise<H5User> {
  const collection = getH5UsersCollection()
  const now = new Date()

  const user: H5User = {
    ...userData,
    createdAt: now,
    updatedAt: now,
  }

  const result = await collection.insertOne(user)
  return { ...user, _id: result.insertedId }
}

/**
 * 根据用户名查找H5用户
 */
export async function findH5UserByUsername(
  username: string
): Promise<H5User | null> {
  const users = getH5UsersCollection()
  return users.findOne({ username })
}

/**
 * 根据邮箱查找H5用户
 */
export async function findH5UserByEmail(email: string): Promise<H5User | null> {
  const collection = getH5UsersCollection()
  return collection.findOne({ email })
}

/**
 * 根据手机号查找H5用户
 */
export async function findH5UserByPhone(phone: string): Promise<H5User | null> {
  const collection = getH5UsersCollection()
  return collection.findOne({ phone })
}

/**
 * 根据ID查找H5用户
 */
export async function findH5UserById(id: string): Promise<H5User | null> {
  const users = getH5UsersCollection()
  return users.findOne({ _id: new ObjectId(id) })
}

/**
 * 获取所有H5用户
 */
export async function getAllH5Users(): Promise<H5User[]> {
  const users = getH5UsersCollection()
  return users.find().toArray()
}

